/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
//
import entity.RedemptionListEntity;
import entity.RedemptionItemEntity;
import entity.ReservedFnBProductEntity;
import entity.ProductEntity;
import entity.ReservedMealEntity;
import entity.ReservedSetMealEntity;
import entity.TouristAccountEntity;
import java.io.IOException;
import util.entityhelper.AccumulationHelper;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import session.stateful.LoyaltyProgramSessionBean;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import org.primefaces.event.SelectEvent;
import session.stateful.VisitorSessionBean;

/**
 *
 * @author NGUYEN CONG DAT
 */
@ManagedBean
@SessionScoped
public class CustomerULPManagerBean {

    @EJB
    private LoyaltyProgramSessionBean loyaltyProgramSessionBean;
    @EJB
    private VisitorSessionBean visitorSessionBean;
    private TouristAccountEntity customer;
    private List<RedemptionItemEntity> redemptionList;
    private RedemptionItemEntity selectedRedemption;
    private AccumulationHelper selectedAccumulation;
    private List<AccumulationHelper> accumulationList;
    private List<RedemptionListEntity> currentULPItemList;
    private RedemptionListEntity selectedULPItem;
    private Integer quantity = 0;
    private Double totalPoint = 0.0;
    private Boolean reloadRedeemPage = false;
    private Boolean voucherExist = false;
    private List<RedemptionItemEntity> redeemedVouchers;
    private String inputReferenceNumber = "";
    private PageRedirectorBean redirect;

    /** Creates a new instance of CustomerULPManagerBean */
    public CustomerULPManagerBean() {
        customer = (TouristAccountEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("tourist");
        loyaltyProgramSessionBean = new LoyaltyProgramSessionBean();
        System.out.println(customer == null);
        accumulationList = new ArrayList<AccumulationHelper>();
        selectedAccumulation = new AccumulationHelper();
        redemptionList = new ArrayList<RedemptionItemEntity>();
        selectedRedemption = new RedemptionItemEntity();
        selectedULPItem = new RedemptionListEntity();
        //currentULPItemList = new List<RedemptionListEntity>();
        redeemedVouchers = new ArrayList<RedemptionItemEntity>();
    }

    public void initViewLoyaltyPointAccount(PhaseEvent event) throws IOException {
        if (!checkCustomer()) {
            return;
        }
        accumulationList = getLoyaltyProgramSessionBean().getAccumulationListByCustomerId(getCustomer().getId());
        redemptionList = getLoyaltyProgramSessionBean().getRedemptionListByCustomerId(getCustomer().getId());

    }

    public boolean checkCustomer() throws IOException {
        redirect = new PageRedirectorBean();
        setCustomer((TouristAccountEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("tourist"));
        if (getCustomer() == null || getCustomer().getId() == null) {
            setCustomer(new TouristAccountEntity());
            redirect.goTouristLoginPageAtPreviousLevel();
            return false;
        }
        return true;
    }

    // not sure whether this works in xhtml file
    public String returnRedemptionStatus(boolean status) {
        if (status == true) {
            return "Voucher Redeemed";
        } else {
            return "Voucher Used";
        }
    }

    public String onRowSelectNavigateViewRedemption(SelectEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("selectedRedemption", selectedRedemption);
        return "tourist/VisitorViewRedemption?faces-redirect=true";
    }

    public String onRowSelectNavigateViewAccumulation(SelectEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("selectedAccumulation", selectedAccumulation);
        return "tourist/VisitorViewAccumulation?faces-redirect=true";
    }

    public void initViewAccumulation(PhaseEvent event) throws IOException {
        selectedAccumulation = (AccumulationHelper) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("selectedAccumulation");
        if (selectedAccumulation == null || selectedAccumulation.getReservation() == null || selectedAccumulation.getReservation().getId() == null) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("tourist/VisitorViewLoyaltyPointAccount.xhtml");
        }
    }

    public void initViewRedemption(PhaseEvent event) throws IOException {
        selectedRedemption = (RedemptionItemEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("selectedRedemption");
        if (selectedRedemption == null || selectedRedemption.getId() == null) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("tourist/VisitorViewLoyaltyPointAccount.xhtml");
        }
    }

    public void initViewCurrentULPItemList(PhaseEvent event) throws IOException {
        customer = (TouristAccountEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("tourist");
        setReloadRedeemPage((Boolean) true);
        quantity = 1;
        currentULPItemList = loyaltyProgramSessionBean.getAllCurrentULPItemEntities();
    }

    public ProductEntity getProductFromReservedFnBProduct(ReservedFnBProductEntity r) {
        ReservedMealEntity meal;
        ReservedSetMealEntity set;
        if (r instanceof ReservedMealEntity) {
            meal = (ReservedMealEntity) r;
            return meal.getMeal();
        } else {
            if (r instanceof ReservedSetMealEntity) {
                set = (ReservedSetMealEntity) r;
                return set.getSetMeal();
            } else {
                return null;
            }
        }
    }

    public void calculateTotalPoint() {
        setTotalPoint((Double) (getQuantity() * selectedULPItem.getPointsToRedeem()));
    }

    public void initVisitorMakeOrder(PhaseEvent event) {
        if (getReloadRedeemPage() == true || totalPoint == 0) {
            totalPoint = selectedULPItem.getPointsToRedeem();
            reloadRedeemPage = false;
        }
    }

    public void redeemULPItem(ActionEvent event) throws IOException {
        try {
            if (totalPoint > customer.getPoint()) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                        FacesMessage.SEVERITY_ERROR, "You do not have enough ULP points to redeem this item", ""));
            } else {
                redeemedVouchers = loyaltyProgramSessionBean.redeemULPItem(customer.getId(), selectedULPItem.getId(), quantity);
                // Refresh customer account
                customer = visitorSessionBean.retrieveVisitorInfoById(customer.getId());
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("customer", customer);
                FacesContext.getCurrentInstance().getExternalContext().redirect("tourist/VisitorViewULPItemRedemptionResult.xhtml");
            }
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "An error occurred ! Item cannot be redeemed !", ""));
            e.printStackTrace();
        }
    }

    public void validateVoucher(ActionEvent event) throws IOException {
        try {
            List<RedemptionItemEntity> list = loyaltyProgramSessionBean.getVoucherByReferenceNumber(inputReferenceNumber);
            if (list.isEmpty()) {
                voucherExist = false;
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                        FacesMessage.SEVERITY_ERROR, "Voucher does not exist", ""));
            } else {
                RedemptionItemEntity voucher = list.get(0);
                selectedRedemption = voucher;
                voucherExist = true;
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                        FacesMessage.SEVERITY_INFO, "Voucher exists", ""));
                FacesContext.getCurrentInstance().getExternalContext().redirect("tourist/VisitorValidateVoucher.xhtml");
            }
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "An error occurred ! Voucher information cannot be retrieved ! Please try again later !", ""));
            e.printStackTrace();
        }
    }

    public LoyaltyProgramSessionBean getLoyaltyProgramSessionBean() {
        return loyaltyProgramSessionBean;
    }

    public void setLoyaltyProgramSessionBean(LoyaltyProgramSessionBean loyaltyProgramSessionBean) {
        this.loyaltyProgramSessionBean = loyaltyProgramSessionBean;
    }

    public TouristAccountEntity getCustomer() {
        return customer;
    }

    public void setCustomer(TouristAccountEntity customer) {
        this.customer = customer;
    }

    public List<RedemptionItemEntity> getRedemptionList() {
        return redemptionList;
    }

    public RedemptionItemEntity getSelectedRedemption() {
        return selectedRedemption;
    }

    public void setSelectedRedemption(RedemptionItemEntity selectedRedemption) {
        this.selectedRedemption = selectedRedemption;
    }

    public List<AccumulationHelper> getAccumulationList() {
        return accumulationList;
    }

    public AccumulationHelper getSelectedAccumulation() {
        return selectedAccumulation;
    }

    public void setSelectedAccumulation(AccumulationHelper selectedAccumulation) {
        this.selectedAccumulation = selectedAccumulation;
    }

    public List<RedemptionListEntity> getCurrentULPItemList() {
        return currentULPItemList;
    }

    public RedemptionListEntity getSelectedULPItem() {
        return selectedULPItem;
    }

    public void setSelectedULPItem(RedemptionListEntity selectedULPItem) {
        this.selectedULPItem = selectedULPItem;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public Double getTotalPoint() {
        return totalPoint;
    }

    public void setTotalPoint(Double totalPoint) {
        this.totalPoint = totalPoint;
    }

    public Boolean getReloadRedeemPage() {
        return reloadRedeemPage;
    }

    public void setReloadRedeemPage(Boolean reloadRedeemPage) {
        this.reloadRedeemPage = reloadRedeemPage;
    }

    public List<RedemptionItemEntity> getRedeemedVouchers() {
        return redeemedVouchers;
    }

    public void setRedeemedVouchers(List<RedemptionItemEntity> redeemedVouchers) {
        this.redeemedVouchers = redeemedVouchers;
    }

    public Boolean getVoucherExist() {
        return voucherExist;
    }

    public void setVoucherExist(Boolean voucherExist) {
        this.voucherExist = voucherExist;
    }

    public String getInputReferenceNumber() {
        return inputReferenceNumber;
    }

    public void setInputReferenceNumber(String inputReferenceNumber) {
        this.inputReferenceNumber = inputReferenceNumber;
    }
}
